/**********************************************************************************
Program:       Real-time Weather Report

License:       GNU/GPL version 3

File:          CurrentCondition.cs

Description:   http连接获取某个城市的实时天气状态

Author:        Guangyu Liu （lgy0417@gmail.com）

Environment:   .NET Framework v2.0 or later version

Usage/Example: README_chs.txt

Last Modified: 2010.08.27

***********************************************************************************/

using System;
using System.IO;
using System.Net;

namespace WeatherInfo
{
	public class CurrentCondition
	{
	
		#region Member Declaration
		
		private string _currentCityID;
		private string _currentURL;
		private string _currentCityName;
		private string _currentObservationTime;
		private string _currentTemp;
		private string _currentWindDirection;
		private string _currentWindSpeed;
		private string _currentHumidity;
		private string _currentAirPressure;
		
		#endregion

		#region Initializer
	
		public string CurrentCityID
		{
			get { return _currentCityID; }
			set {
				_currentCityID = value;
				_currentURL = "http://www.weather.com.cn/data/sk/" + _currentCityID + ".html";
				GetData();
			}
		}
	
		private void GetData()
		{
			HttpWebRequest wrGETURL;
			try
			{
				wrGETURL = (HttpWebRequest)WebRequest.Create(_currentURL);
				wrGETURL.UserAgent = "Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.0; .NET CLR 1.1.4322)";
				Stream objStream;
				objStream = wrGETURL.GetResponse().GetResponseStream();
				StreamReader htmlReader;
				htmlReader = new StreamReader(objStream, System.Text.Encoding.GetEncoding("utf-8"));
				
				/* Get html content */
				string htmlContent;
				htmlContent = htmlReader.ReadToEnd();
				
				/* Pick out useful info */
				string[] htmlContentsplit = htmlContent.Split('"');
				_currentCityName = htmlContentsplit[5];
				_currentObservationTime = htmlContentsplit[41];
				_currentTemp = htmlContentsplit[13];
				_currentWindDirection = htmlContentsplit[17];
				_currentWindSpeed = htmlContentsplit[45];
				_currentHumidity = htmlContentsplit[25];
				_currentAirPressure = htmlContentsplit[29];
				
				/* 由错误的城市代码引起的“找不到URL”错误 */
				if (_currentTemp == "960")
					throw new WrongCityNameException();
			}
			catch (WebException we)
			{
				_currentObservationTime = _currentTemp = _currentWindDirection = _currentWindSpeed
				= _currentHumidity = _currentAirPressure = "-";
				throw we;
			}
			catch (WrongCityNameException wcne)
			{
				_currentObservationTime = _currentTemp = _currentWindDirection = _currentWindSpeed
				= _currentHumidity = _currentAirPressure = "-";
				throw wcne;
			}
			catch (Exception dataFetchingFailure)
			{
				_currentObservationTime = _currentTemp = _currentWindDirection = _currentWindSpeed
				= _currentHumidity = _currentAirPressure = "-";
				throw dataFetchingFailure;
			}
		}

		#endregion

		#region Constructor

		public CurrentCondition()
		{ }

		#endregion
		
		#region Properties
		
		public string CurrentObservationTime
		{
			get { return _currentObservationTime; }
		}
		
		public string CurrentTemp
		{
			get { return _currentTemp; }
		}
		
		public string CurrentWindDirection
		{
			get { return _currentWindDirection; }
		}
		
		public string CurrentWindSpeed
		{
			get { return _currentWindSpeed; }
		}
		
		public string CurrentHumidity
		{
			get { return _currentHumidity; }
		}
	
		public string CurrentAirPressure
		{
			get { return _currentAirPressure; }
		}
		
		#endregion
		
		
		// public void ConsoleDisplay()
		// {
			// Console.WriteLine("城市名称:              " + _currentCityName);
			// Console.WriteLine("观测时间：             " + _currentObservationTime);
			// Console.WriteLine("实时气温：             " + _currentTemp + " \u00B0" + "C");
			// Console.WriteLine("实时风向：             " + _currentWindDirection);
			// Console.WriteLine("实时风速：             " + _currentWindSpeed + " m/s");
			// Console.WriteLine("实时湿度：             " + _currentHumidity);
			// Console.WriteLine("实时气压：             " + _currentAirPressure);
		// }
		
		
		/* Method Main() for testing Class CurrentCondition */
		// public static void Main()
		// {
			// Console.Write("Fetching and analyzing data from Web......");
			// DateTime p = DateTime.Now;
			// CurrentCondition cc = new CurrentCondition();
			// cc.CurrentCityID = "101010100";
			// Console.WriteLine("Done!\n");
			// cc.ConsoleDisplay();
			// DateTime n = DateTime.Now;
			// Console.WriteLine("\nTime Elapsed: {0} ms", n.Subtract(p).TotalMilliseconds);
		// }
	}
	
	
	public class WrongCityNameException : Exception
	{
		private const string msg = "城市名称有误：请不要用外国地名、中国省级区划以及基层乡镇村的名称";

		internal WrongCityNameException() : base(msg)
		{ }

		internal WrongCityNameException(string str) : base(String.Format( "{0} - {1}", str, msg))
        { }
	}

}
